package com.lt.flashcard.model.service;

import java.util.Iterator;
import java.util.List;

import org.bson.types.ObjectId;

import com.google.code.morphia.dao.BasicDAO;
import com.google.code.morphia.query.Query;
import com.lt.flashcard.model.entity.TaskQueue;

public class TaskService {

	private BasicDAO<TaskQueue, ObjectId> dao = new BasicDAO<TaskQueue, ObjectId>(TaskQueue.class, Repository.getInstance().getDatastore());
	public static final String QUEUE_UPDATEFLASHCARDSET = "updatefcs";
	
	/**
	 * Save a task in database
	 * @param task
	 */
	public void saveTask(TaskQueue task) {
		dao.save(task);
	}
	
	public void deleteTask(TaskQueue task) {
		dao.delete(task);
	}
	
	public TaskQueue getTask(String id) {
		return dao.get(new ObjectId(id));
	}
	
	/**
	 * Admin can make change to flashcardset of blueup, after that schedule to apply the change for all production
	 * @param fcsid
	 * @param setimage
	 * @param setdetail
	 * @param cardimage
	 * @param carddetail
	 */
	public void addTaskUpdateFlashcardSet(Long fcsid, boolean setimage, boolean setdetail, boolean cardimage, boolean carddetail) {
		TaskQueue task = new TaskQueue();
		task.setDescription(String.format("Change update for flashcardset id %s", fcsid));
		task.setName(QUEUE_UPDATEFLASHCARDSET);
		task.setParam("fcsid", fcsid);
		task.setParam("setimage", setimage);
		task.setParam("setdetail", setdetail);
		task.setParam("cardimage", cardimage);
		task.setParam("carddetail", carddetail);
		
		saveTask(task);
	}
	
	public TaskQueue getTaskUpdateFlashcardSet(Long fcsid) {
		Query<TaskQueue> query = dao.createQuery();
		query.field("name").equal(QUEUE_UPDATEFLASHCARDSET);
		query.order("-created");
		List<TaskQueue> rs = query.asList();
		Iterator<TaskQueue> it = rs.iterator();
		while(it.hasNext()) {
			TaskQueue t = it.next();
			if(t.getParam("fcsid").equals(fcsid))
				return t;
		}
		return null;
	}
}
